<template>
  <view class="container">
    <view class="form">
      <text class="title">登录</text>
      
      <!-- 用户名输入框 -->
      <input 
        class="input" 
        placeholder="请输入用户名" 
        v-model="username" 
        @focus="handleInputFocus('username')"
        @blur="handleInputBlur('username')"
      />
      <text class="error-tips" v-if="showError.username">{{ errorMsg.username }}</text>
      
      <!-- 密码输入框 -->
      <input 
        class="input" 
        placeholder="请输入密码" 
        type="password" 
        v-model="password" 
        @focus="handleInputFocus('password')"
        @blur="handleInputBlur('password')"
      />
      <text class="error-tips" v-if="showError.password">{{ errorMsg.password }}</text>
      
      <!-- 记住密码复选框 -->
      <view class="remember-wrap">
        <checkbox 
          v-model="rememberPwd" 
          color="#007aff"
          class="remember-checkbox"
        ></checkbox>
        <text class="remember-text">记住密码</text>
      </view>
      
      <!-- 登录按钮 -->
      <button class="btn" type="primary" @click="handleLogin" :loading="isLoading">登录</button>
      
      <!-- 注册链接 -->
      <view class="link">
        <navigator url="/pages/register/register" class="register-link">没有账号？去注册</navigator>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      rememberPwd: false, // 是否记住密码
      isLoading: false, // 登录加载状态
      showError: { // 表单错误显示状态
        username: false,
        password: false
      },
      errorMsg: { // 表单错误提示
        username: '用户名不能为空',
        password: '密码不能为空'
      }
    };
  },
  onLoad() {
    // 页面加载时，自动填充记住的密码（如果有）
    this.getRememberedUserInfo();
  },
  onShow() {
    // 每次页面显示时，检查是否已登录（防止后退到登录页）
    this.checkLoginStatus();
  },
  methods: {
    // 输入框聚焦：隐藏错误提示
    handleInputFocus(type) {
      this.showError[type] = false;
    },
    // 输入框失焦：校验必填项
    handleInputBlur(type) {
      if (!this[type]) {
        this.showError[type] = true;
      }
    },
    // 获取本地存储的用户信息（记住密码功能）
    getRememberedUserInfo() {
      const rememberedUser = uni.getStorageSync('rememberedUser');
      if (rememberedUser) {
        // 检查存储是否过期（7天有效期）
        const now = new Date().getTime();
        if (now - rememberedUser.expireTime <= 7 * 24 * 60 * 60 * 1000) {
          this.username = rememberedUser.username;
          this.password = rememberedUser.password;
          this.rememberPwd = true;
        } else {
          // 过期则清除存储
          uni.removeStorageSync('rememberedUser');
        }
      }
    },
    // 检查登录状态（防止已登录后后退到登录页）
    checkLoginStatus() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        // 已登录，直接跳转到首页（路径与tabBar配置一致）
        uni.switchTab({
          url: "/pages/tabBar/demos/news/news"
        });
      }
    },
    // 表单校验
    validateForm() {
      let isPass = true;
      // 用户名校验
      if (!this.username.trim()) {
        this.showError.username = true;
        this.errorMsg.username = '用户名不能为空';
        isPass = false;
      } else if (this.username.trim().length < 3) {
        this.showError.username = true;
        this.errorMsg.username = '用户名长度不能少于3位';
        isPass = false;
      }
      
      // 密码校验
      if (!this.password.trim()) {
        this.showError.password = true;
        this.errorMsg.password = '密码不能为空';
        isPass = false;
      } else if (this.password.trim().length < 6) {
        this.showError.password = true;
        this.errorMsg.password = '密码长度不能少于6位';
        isPass = false;
      }
      
      return isPass;
    },
    // 登录逻辑
    handleLogin() {
      // 1. 先执行表单校验
      if (!this.validateForm()) return;
      
      // 2. 模拟登录请求
      this.isLoading = true;
      
      // 模拟接口延迟
      setTimeout(() => {
        // 模拟正确账号密码
        const correctUsername = 'xin';
        const correctPassword = '123456';
        
        if (this.username === correctUsername && this.password === correctPassword) {
          // 登录成功：存储用户信息
          const userInfo = {
            userId: '1001',
            username: this.username,
            nickname: '测试用户'
          };
          uni.setStorageSync('userInfo', userInfo);
          
          // 记住密码逻辑
          if (this.rememberPwd) {
            uni.setStorageSync('rememberedUser', {
              username: this.username,
              password: this.password,
              expireTime: new Date().getTime()
            });
          } else {
            uni.removeStorageSync('rememberedUser');
          }
          
          // 跳转到首页
          uni.switchTab({
            url: "/pages/demos/news/news",
            success: () => {
              uni.showToast({ title: '登录成功' });
            }
          });
        } else {
          // 登录失败：提示错误
          uni.showToast({
            title: '用户名或密码错误',
            icon: 'none',
            duration: 1500
          });
        }
        
        this.isLoading = false;
      }, 1000);
    }
  }
};
</script>

<style scoped>
/* 容器：柔和背景+居中布局 */
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f8f9fa; /* 更柔和的背景色 */
  padding: 30rpx;
}

/* 表单：卡片式设计+柔和阴影 */
.form {
  width: 100%;
  max-width: 550rpx;
  background-color: #ffffff;
  padding: 50rpx 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05); /* 更柔和的阴影 */
}

/* 标题：醒目且沉稳 */
.title {
  display: block;
  font-size: 42rpx;
  font-weight: 700;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 50rpx;
}

/* 输入框：圆角+柔和边框+聚焦动画 */
.input {
  width: 100%;
  padding: 22rpx 24rpx;
  margin-bottom: 15rpx;
  border: 1rpx solid #e5e7eb;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #2c3e50;
  transition: border-color 0.2s ease; /* 聚焦过渡动画 */
}
.input::placeholder {
  color: #9ca3af; /* 占位符淡色 */
}
.input:focus {
  border-color: #007aff; /* 聚焦时高亮边框 */
  outline: none;
}

/* 错误提示：醒目但不刺眼 */
.error-tips {
  display: block;
  font-size: 26rpx;
  color: #ef4444;
  margin-bottom: 20rpx;
  height: 26rpx;
  line-height: 26rpx;
}

/* 记住密码：对齐更美观 */
.remember-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 35rpx;
  font-size: 28rpx;
  color: #6b7280;
}
.remember-checkbox {
  transform: scale(1.2); /* 放大复选框，更易点击 */
  margin-right: 12rpx;
}
.remember-text {
  line-height: 32rpx;
}

/* 登录按钮：饱满+圆角+强调色 */
.btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #ffffff;
  background-color: #007aff;
  border-radius: 12rpx;
  margin-bottom: 35rpx;
}
.btn::after {
  border-radius: 12rpx; /* 修复uni-app按钮默认边框圆角问题 */
}
.btn:active {
  background-color: #0066cc; /* 点击时加深颜色，提升交互感 */
}

/* 注册链接：色彩呼应+清晰区分 */
.link {
  text-align: center;
  font-size: 28rpx;
  color: #6b7280;
}
.register-link {
  color: #007aff;
  font-weight: 500;
  margin-left: 8rpx;
}
</style>